Display Fibonacci Sequence in C Program

07-11-17 Course- C

Example to read how to display the Fibonacci sequence of first n numbers (entered by the user) using loop. Also in different example, you learn to generate the Fibonacci sequence up to a certain number.

The Fibonacci sequence is a series where the next term is the sum of pervious two terms. The first two terms of the Fibonacci sequence is 0 followed by 1.


The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21

Visit this page to learn about Fibonacci sequence.

Example N.1: Fibonacci Series up to n number of terms


#include <stdio.h>
int main()
{
    int i, n, t1 = 0, t2 = 1, nextTerm = 0;

    printf("Enter the number of terms: ");
    scanf("%d",&n);

    // displays the first two terms which is always 0 and 1
    printf("Fibonacci Series: %d, %d, ", t1, t2);

    // i = 3 because the first two terms are already dislpayed
    for (i=3; i <= n; ++i)
    {
        nextTerm = t1 + t2;
        t1 = t2;
        t2 = nextTerm;
        printf("%d, ",nextTerm);
    }
    return 0;
}

Output


Enter the number of terms: 10
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 

Example N.2: Program to Generate Fibonacci Sequence Up to a Certain Number


#include <stdio.h>
int main()
{
    int t1=0, t2=1, nextTerm = 0, n;

    printf("Enter a positive integer: ");
    scanf("%d",&n);

    // displays the first two terms which is always 0 and 1
    printf("Fibonacci Series: %d, %d, ", t1, t2);

    nextTerm = t1+t2;

    while(nextTerm < n)
    {
        printf("%d, ",nextTerm);
        t1 = t2;
        t2 = nextTerm;
        nextTerm = t1+t2;
    }
    
    return 0;
}

Output


Enter a positive integer: 100
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,